<?php
class Response{
	CONST JSON = 'json';

	//在设置传参默认值时只能设置常量，使用变量报错
	public static function format($code=200,$message='',$data=array(),$type=self::JSON){

		if(!empty($_GET['type'])) $type = $_GET['type'];
		if($type=='json'){
			$method = 'toJson';
		}elseif($type=='xml'){
			$method = 'toXml';
		}else{
			//todo
		}
		
		return self::$method($code,$message,$data); 
	}
	
	public static function toJson($code,$message,$data){
	
		if(!is_numeric($code)){
			return '';
		}
		
		$arr = array(
			'code' => $code,
			'message' => $message,
			'data' => $data,
		);
		
		return json_encode($arr);
	}
	
	public static function toXml($code,$message,$data){
		header('Content-Type:text/xml');
		$xml = "<?xml version='1.0' encoding='UTF-8'?>";
		$xml .= '<root>';
		$xml .= '<code>'.$code;
		$xml .= '</code>';
		$xml .= '<message>'.$message;
		$xml .= '</message>';
		$xml .= self::parseDataToXml($data);
		$xml .= '</root>';
		return $xml;
	}
	
	protected static function parseDataToXml($data){
		$xml = '';
		if(is_array($data) && count($data)>0){
			foreach($data as $key=>$val){
				$attr = '';
				if(is_numeric($key)){
					$attr = "id='{$key}'";
					$key = 'item';
				}
				
				$xml .= "<{$key} {$attr}>";
				$xml .= (!is_array($val))?"{$val}":self::parseDataToXml($val);
				$xml .= "</{$key}>";
			}
		}
		return $xml;
	}	
}